package com.blog4j.user.schedule;

import cn.hutool.core.collection.CollectionUtil;
import com.blog4j.common.constants.CacheConstants;
import com.blog4j.common.utils.RedisUtil;
import com.blog4j.user.mapper.UserIllegalRecordMapper;
import com.blog4j.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * @author 98k灬
 * @version v1.0.0
 * @Description : 功能描述
 * @Create on : 2024/8/18 10:28
 **/
@Component
@EnableScheduling
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UserSchedule {
    private final RedisUtil redisUtil;
    private final UserIllegalRecordMapper userIllegalRecordMapper;
    private final UserMapper userMapper;
    private static final int USER_ILLEGAL_ACTION_MAX_TIMES = 3;

    // 每个月1号凌晨1秒执行
    @Scheduled(cron = "1 0 0 1 * ?")
    public void clearUserMonthUpdatePwdTimes() {
        Set<String> keys = redisUtil.keys(CacheConstants.USER_UPDATE_PWD_TIMES_KEY);
        if (CollectionUtil.isEmpty(keys)) {
            return;
        }
        for (String key : keys) {
            redisUtil.del(key);
        }
    }

    // 每隔半小时执行一次  封禁不合法用户
    @Scheduled(cron = "0 */30 * * * ?")
    public void banIllegalUser() {
        List<String> userIds = userIllegalRecordMapper.getIllegalUser(USER_ILLEGAL_ACTION_MAX_TIMES);
        if (CollectionUtil.isEmpty(userIds)) {
            return;
        }

        // 批量更新用户状态为锁定
        userMapper.batchLockUser(userIds);
    }
}

